//删除链表中等于给定值 val 的所有节点。 
//
// 示例: 
//
// 输入: 1->2->6->3->4->5->6, val = 6
//输出: 1->2->3->4->5
// 
// Related Topics 链表

package leetcode.editor.cn;
public class RemoveLinkedListElements {
    public static void main(String[] args) {
        Solution solution = new RemoveLinkedListElements().new Solution();
        ListNode listNode = ListNodeUtil.constructList(new int[]{6,1, 2, 6, 3, 4, 5, 6});
//        ListNode listNode = ListNodeUtil.constructList(new int[]{1, 2, 6, 3, 4, 5, 6});
        ListNode node = solution.removeElements(listNode, 6);

        ListNodeUtil.printList(node);
    }
    
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }

        ListNode p = head;
        ListNode prev = null;
        while (p != null) {
            if (p.val == val) {
                // 当前为头节点
                if (prev == null) {
                    head = p.next;
                    prev = null;
                    p = p.next;
                    continue;
                } else {
                    prev.next = p.next;
                    p = p.next;
                    continue;
                }
            } else {
                prev = p;
                p = p.next;
            }
        }

        return head;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}